import html2canvas from "html2canvas";
/**
 * @name 生成截图
 * @param {Element} canvasBox 截图区域dom对象
 */
export const createScreenshot = (canvasBox, down = true) => {
	return new Promise((resolve,reject) => {
		// 手动创建一个 canvas 标签
		const canvas = document.createElement('canvas')
		// 获取父级的宽高
		const width = parseInt(canvasBox.width)
		const height = parseInt(canvasBox.height)
		// 宽高 * 2 并放大 2 倍 是为了防止图片模糊
		canvas.width = width * 2
		canvas.height = height * 2
		canvas.style.width = width + 'px'
		canvas.style.height = height + 'px'
		const context = canvas.getContext('2d')
		context.scale(2, 2)
		html2canvas(canvasBox, {
			allowTaint: true
		}).then((canvas) => {
			//转换base64
			const capture = canvas.toDataURL('image/png', 0.5)
			//下载浏览器弹出下载信息的属性
			const date = new Date()
			const saveInfo = {
				//导出文件格式自己定义，我这里用的是时间作为文件名
				download: date.getTime() + `.png`,
				href: capture,
			}
			//下载，浏览器弹出下载文件提示
			down && downloadFile(saveInfo)
			resolve(capture)
		}).catch(err => {
			reject(err)
		})
	})
}

function getStyle(element, property){
    var proValue = null;
    if (!document.defaultView) {
        proValue = element.currentStyle[property];
    } else {
        proValue = document.defaultView.getComputedStyle(element)[property];
    }
    return proValue;
}

/**
 * @name 下载文件
 * @param {Object} saveInfo 下载参数内容
 */
export const downloadFile = (saveInfo) => {
	const element = document.createElement('a')
	element.style.display = 'none'
	for (const key in saveInfo) {
		element.setAttribute(key, saveInfo[key])
	}
	document.body.appendChild(element)
	element.click()
	setTimeout(() => {
		document.body.removeChild(element)
	}, 300)
}
/**
 * @name 时间格式转换
 * @param {timestamp} Number 下载参数内容
 */
export const useDateFormat = (timestamp = '') => {
	let d = new Date(timestamp)
	let year = d.getFullYear()
	let month = supplyZero(d.getMonth() + 1)
	let day = supplyZero(d.getDate())
	let hour = supplyZero(d.getHours())
	let min = supplyZero(d.getMinutes())
	let second = supplyZero(d.getSeconds())
	return `${year}-${month}-${day} ${hour}:${min}:${second}`
}
// 个位数补零
export const supplyZero = (num) => {
	return num < 10 ? `0${num}` : num
}
